package com.groupbuying.generator.controller;

import com.groupbuying.generator.service.GeneratorService;
import com.groupbuying.generator.utils.PageUtils;
import com.groupbuying.generator.utils.Query;
import com.groupbuying.generator.utils.apiresult.ApiResult;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RequestMapping()
@RestController
public class GeneratorController {
    @Autowired
    GeneratorService generatorService;


    /**
     * 搜索数据库表
     */
    @ApiOperation(value = "搜索数据库列表", notes = "搜索数据库列表")
    @GetMapping("/doSearch")
    public ApiResult doSearch(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        List<Map<String, String>> list = generatorService.doSearch(query);
        int total = list.size();
        PageUtils pageUtil = new PageUtils(list, total);
        return ApiResult.success(pageUtil);
    }

    /**
     * 查询数据库列表
     */
    @ApiOperation(value = "查询数据库列表", notes = "查询数据库列表")
    @GetMapping("/getDBList")
    public ApiResult getDBList(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        List<Map<String, Object>> list = generatorService.list(query);
        int total = generatorService.count();
        PageUtils pageUtil = new PageUtils(list, total);
        return ApiResult.success(pageUtil);
    }


    @GetMapping("/createCode/{tableName}&{name}&{packageName}&{email}")
    public void createCode(HttpServletResponse response,
                           @PathVariable("tableName") String tableName,
                           @PathVariable("name") String name,
                           @PathVariable("packageName") String packageName,
                           @PathVariable("email") String email
    ) throws IOException {
        String[] tableNames = new String[]{tableName};
        byte[] data = generatorService.generatorCode(tableNames, name, packageName, email);
        String date = new Date().toString();
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + date + ".zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}
